import BScroll from "better-scroll";
import {bindDrainageScene} from "../../fun/modules/drainage_scene.js";
import groupListCell from "components/goods/children/plugin/groupListCell";

export default {
  data() {
    return {
      Data: {},
      showAll: true, //内容是否全部展示
      time: "",
      Day: "", //剩余天
      Hour: "", //剩余小时
      Min: "", //剩余分钟
      Sec: "", //剩余秒
      stop: false, //判断活动是否结束
      songStop: true, //判断停止还是播放
      end: "", //活动结束时间
      commission_amount: [], //排行榜数据
      orders: [], //返回的订单列表数据
      readyState: 0, //音频是否加载完成
      clientWidths: "",
      browse_count: "", //浏览人数
      award_count: "",
      buy_count: "",
      sales_count: "",
      show: false,
      store_id: "",

      poster_open: 0,
      poster_show: false,
      poster_url: "",

      style: 0,//浏览记录样式
      browseLoadMore: true,
      browsePage: 1,
      browseData: [],

      groupPage: 1,
      groupData: [],
      groupLoadMore: true,
      showGroupPop: false,
      uid: null,
    };
  },
  activated() {
    this.show = false;
    this.store_id = this.$route.query.store_id;
    this.initData();
    this.getData();

    this.clientWidths = document.body.clientWidth;
  },
  mounted() {
    this.clientWidths = document.body.clientWidth;
    // this.autoPlayAudio2();
  },
  methods: {
    initData() {
      this.Data = {};
      this.showAll = true; //内容是否全部展示
      this.time = "";
      this.Day = ""; //剩余天
      this.Hour = ""; //剩余小时
      this.Min = ""; //剩余分钟
      this.Sec = ""; //剩余秒
      this.stop = false; //判断活动是否结束
      this.songStop = true; //判断停止还是播放
      this.browse_member = []; //浏览头像
      this.commission_amount = []; //排行榜数据
      this.orders = []; //返回的订单列表数据
      this.readyState = 0;
      this.clientWidths = "";
      this.browse_count = 0;

      this.poster_open = 0;
      this.poster_show = false;
      this.poster_url = "";
      if(this.$route.query.share_tag) this.share_uid = this.$route.query.mid||null;//从分享链接或者二维码进入，分享者id

      this.groupPage = 1;
      this.groupLoadMore = true;
      this.groupData = [];
      this.browsePage = 1;
      this.browseLoadMore = true;
      this.browseData = [];
    },
    _initScrollCart() {
      this.storeScroll = new BScroll(this.$refs.store, {
        click: true
      });
    },
    _initScrollCart1() {
      this.storeScroll1 = new BScroll(this.$refs.store1, {
        click: true
      });
    },
    showStore() {
      this.$nextTick(() => {
        if (this.Data.award_list == 1) {
          if (!this.storeScroll) {
            this._initScrollCart();
          } else {
            this.storeScroll.refresh();
          }
        }

        if (this.Data.order_list == 1) {
          if (!this.storeScroll1) {
            this._initScrollCart1();
          } else {
            this.storeScroll1.refresh();
          }
        }
      });
    },
    //获取数据
    getData() {
      let json = {
        activity_id: this.fun.getKey("activity_id")
      };
      $http
        .get("plugin.share-activity.frontend.activity.index", json, "获取中")
        .then(response => {
          if (response.result == 1) {
            this.Data = response.data;
            if (this.Data.audio_link) {
              this.autoPlay();
            }

            let _html = response.data.agreement.replace(/<video /g, '<video webkit-playsinline="true" playsinline="true" ');
            this.Data.agreement = _html;

            this.store_id = this.Data.store_id;
            this.browse_count = this.Data.browse_count;
            this.browse_member = this.Data.browse_member;
            this.end = this.Data.end_time;
            this.poster_open = this.Data.poster_open || 0;
            this.fun.setWXTitle(this.Data.name);
            this.countdown();

            if (this.Data.award_list == 1) {
              this.getAwardData();
            }
            if (this.Data.open_group_list == 1) {
              this.uid = window.localStorage.getItem("uid");
              this.getGroupData();
            }
            this.getOrderData();
            this.style = this.Data.style;
            if (this.style == 1) {
              this.getBrowseList();
            }
            this.fun.wxShare(
              "",
              {},
              {
                title: this.Data.share_title ? this.Data.share_title : "",
                imgUrl: this.Data.share_thumb ? this.Data.share_thumb : "",
                description: this.Data.share_content ? this.Data.share_content : ""
              }
            );

          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取购买列表
    getOrderData() {
      let json = {
        activity_id: this.fun.getKey("activity_id")
      };
      $http
        .get("plugin.share-activity.frontend.activity.getOrders", json, "获取中")
        .then(response => {
          if (response.result === 1) {
            this.buy_count = response.data.buy_count;
            this.sales_count = response.data.sales_count;
            this.orders = response.data.orders;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取奖励列表
    getAwardData() {
      let json = {
        activity_id: this.fun.getKey("activity_id")
      };
      $http
        .get("plugin.share-activity.frontend.activity.getAwards", json, "获取中")
        .then(response => {
          if (response.result == 1) {
            this.award_count = response.data.award_count;
            this.commission_amount = response.data.awards;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    async getGroupData(){
      if(!this.groupLoadMore) return;
      let { result, msg, data } = await $http.get('plugin.share-activity.frontend.activity.all-team',{
        id: this.Data.group_id,
        page: this.groupPage
      },".");
      if(result == 0) return this.$toast(msg);
      this.groupPage += 1;
      this.groupData = this.groupData.concat(data.data);
      if(data.last_page == data.current_page) this.groupLoadMore = false;
    },
    async getBrowseList(more){
      if(!this.browseLoadMore || this.browsePage > 8) return;
      let { result, msg, data } = await $http.get('plugin.share-activity.frontend.activity.browse-member',{
        activity_id: this.fun.getKey("activity_id"),
        page: this.browsePage
      },".");
      if(result == 0) return this.$toast(msg);

      this.browsePage += 1;
      let chunkedArray = this.chunkArray(data.data, 5);
      this.browseData = this.browseData.concat(chunkedArray);
      if(data.last_page == data.current_page) this.browseLoadMore = false;
      if(more) {
        this.$nextTick(() => {
          this.$refs.browseSwipe.swipeTo(this.activeIndex,{immediate: true});
        });
      }
    },
    chunkArray(arr, chunkSize) {
      // 拆分数组
      let result = [];
      for (let i = 0; i < arr.length; i += chunkSize) {
        result.push(arr.slice(i, i + chunkSize));
      }
      return result;
    },
    changeSwipe(e){
      if(this.browseData.length == e + 2) {
        this.activeIndex = this.$refs.browseSwipe.active;
        this.getBrowseList(true);
      }
    },
    //活动倒计时
    countdown() {
      // 当前时间戳
      const now = Date.parse(new Date()) / 1000;
      if (this.end - now <= 0) {
        this.stop = true;
        return;
      }

      let msec = 0;
      if (now >= this.Data.star_time) {
        // 相差的秒数
        msec = this.end - now;
      } else {
        msec = this.Data.star_time - now;
      }

      // 计算的时间
      let day = parseInt(msec / 60 / 60 / 24);

      let hr = parseInt((msec / 60 / 60) % 24);
      let min = parseInt((msec / 60) % 60);
      let sec = parseInt(msec % 60);
      // 个位数前补零
      hr = hr > 9 ? hr : "0" + hr;
      min = min > 9 ? min : "0" + min;
      sec = sec > 9 ? sec : "0" + sec;
      // 控制台打印
      // this.time=`${day}天 ${hr}小时 ${min}分钟 ${sec}秒`
      (this.Day = day), (this.Hour = hr), (this.Min = min), (this.Sec = sec);
      // 一秒后递归
      setTimeout(() => {
        this.countdown();
      }, 1000);
    },
    onLoadedmetadata(res) {
      this.readyState = this.$refs.audio.readyState;
      this.autoPlay();
    },
    play_audio(){
      console.log("点击页-播放钟====")
      this.play();
    },
    pause(){
      this.$refs.audio.pause();
      this.songStop = true;
    },
    // 歌曲播放
    play() {
      console.log(this.$refs.audio,"this.$refs.audio===",this.$refs.audio.paused);
      this.$nextTick(() => {
          this.$refs.audio.play();
          this.songStop = false;
      });
    },
    autoPlay() {
      const that = this;
      this.$refs.audio.play();
      if (this.fun.isWeiXin()) {
        document.addEventListener(
          "WeixinJSBridgeReady",
          function() {
            that.$refs.audio.play();
            that.songStop = false;
          },
          false
        );
      }else {
        this.songStop = true;
      }
    },
    //跳转到商品详情
    toGoods(extinfo = {}) {
      let isBindDrainageScene = bindDrainageScene({
        scene: 9,
        title: this.Data.name
      });
      if(!isBindDrainageScene) return;//爆客码绑定场景

      if (Date.parse(new Date()) / 1000 < this.Data.star_time) {
        this.$dialog.alert({ message: "目前还没到开始时间" });
        return;
      }
      if (Date.parse(new Date()) / 1000 > this.Data.end_time) {
        this.$dialog.alert({ message: "活动时间已结束" });
        return;
      }
      let _orderJson = {
        goodsId: this.Data.goods_id,
        optionsId: this.Data.option_id,
        total: this.Data.total
      };
      let _queryJson = {
        store_id: this.store_id
      };
      if (this.Data.group_id) {
        _queryJson.activityType = 'GroupGoods';
        _queryJson.id = this.Data.group_id;
      }
      if(this.store_id) _orderJson.store_id = this.store_id;

      if(this.share_uid) _orderJson.share_uid = this.share_uid;//分享者奖励需要
      _orderJson.activity_id = this.fun.getKey("activity_id");

      if (this.Data.diyform_id) {
        this.$router.push(
          this.fun.getUrl(
            "activityDiyForm",
            {
              id: this.Data.diyform_id,
              ..._orderJson
            },_queryJson
          )
        );
      } else {
        if(extinfo.activityType == 'GroupDetail') {
          let _json = { id: this.groupDetailID};
          if (this.Data.store_id) {
            _json.store_id = this.Data.store_id;
          }
          return this.$router.push(this.fun.getUrl("GroupDetail", _json,{share_uid: this.share_uid || 0, activity_id: this.fun.getKey("activity_id")}));
        }
        if (this.Data.group_id) {
          return this.$router.push(this.fun.getUrl("GroupGoods",{id: this.Data.group_id,store_id:this.Data.store_id||0},{share_uid: this.share_uid || 0, activity_id: this.fun.getKey("activity_id")}));
        }
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              tag: "-2", //立即购买,
              ..._orderJson
            }
          )
        );
      }
    },
    swipeToTop(index) {
      if (index === this.commission_amount.length - 2) {
        this.$refs.swipe.swipeTo(0);
      }
      if (index === this.orders.length - 2) {
        this.$refs.swipe1.swipeTo(0);
      }
    },
    autoPlayAudio2() {
      const that = this;
      wx.config({
        // 配置信息, 即使不正确也能使用 wx.ready
        debug: false,
        appId: "",
        timestamp: 1,
        nonceStr: "",
        signature: "",
        jsApiList: []
      });
      wx.ready(function() {
        that.$refs.audio.play();
      });
    },
    //悬浮按钮跳转
    linkTo(str) {
      if (str == "order") {
        if(this.Data.open_group_list === 1) return this.$router.push(this.fun.getUrl("GroupOrderlist", { status: "0" ,orderType: 'groups'}));
        this.$router.push(this.fun.getUrl("orderlist", { status: "0" }));
      } else if (str == "member") {
        this.$router.push(this.fun.getUrl("member"));
      } else {
        this.show = true;
      }
    },
    getPosterImage() {
      if (this.poster_url != "") {
        this.poster_show = true;
        return;
      }
      let json = {
        activity_id: this.fun.getKey("activity_id")
      };
      $http.get("plugin.share-activity.frontend.activity.get-poster", json, "获取中").then(response => {
        if (response.result == 1) {
          console.log(response.data.poster);
          this.poster_url = response.data.poster;
          this.poster_show = true;
        }
      });
    },
    finishTwo(index) {
      this.groupData.splice(index, 1); //删除下标为i的元素
    },
    //加入该团按钮
    clickAdd(event, _id,item) {
      this.showGroupPop = false;
      this.groupDetailID = _id;
      this.toGoods({activityType: 'GroupDetail'});
    },
    goto() {
      if (window.history.length <= 1) {
        this.$router.push(this.fun.getUrl("home", {}));
      } else {
        this.$router.go(-1);
      }
    },
  },
  components: {groupListCell}
};
